package 剑指offer;

/**
 * Created by IntelliJ IDEA.
 *
 * @ProjectName leetcode
 * @Author Ding
 * @CreateTime 2022/8/27 10:45 星期六
 */
public class _53_在排序数组中查找数字1 {
    public static void main(String[] args) {
        int[] nums = new int[]{5,7,7,8,8,10};
        System.err.println(search(nums,8));
    }

    public static int search(int[] nums, int target) {
        int lp = 0;
        int rp = nums.length-1;
        while (lp<=rp){
            int mid = lp + (rp-lp)/2;
            if (nums[mid] < target){
                lp = mid+1;
            }else if (nums[mid] > target){
                rp = mid - 1;
            }else{
                lp = mid - 1;
                rp = mid;
                int n = 0;
                while (lp >= 0 && nums[lp--] == target){
                    n++ ;
                }
                while (rp < nums.length && nums[rp++] == target){
                    n++;
                }
                return n;
            }
        }
        return 0;
    }
}
